<!-- 表格设计器 -->
<template>
  <div>
    <ele-form
      :isResponsive="true"
      :span="24"
      :formDesc="formDesc"
      :isShowSubmitBtn="false"
      :isShowErrorNotify="false"
      :isShowBackBtn="false"
      v-model="tableData"
      @update:visible="$emit('change', $event)"
      :request-fn="handleRequest"
      @request-success="handleRequestSuccess"
    ></ele-form>
  </div>
</template>

<script>
import setColumn from './setColumn.vue'
import { COLUMN_TYPE, INPUT_TYPE } from '../../const/applyForm/tableCreator'
import { formatColumnContent } from './utils'
export default {
  data() {
    return {
      loading: false,
      formDesc: {
        "key_66": {
          label: '',
          type: 'table-editor',
          attributes: [],  // 放每列的指标值设置值
          attrs: {
            isShowAdd: true,
            isShowDelete: true,
            // 校检规则
            rules: {},
            // 其它按钮
            extraBtns: [],
            // 表格列
            columns: [],
            // 新行默认值
            newColumnValue: {}
          }
        }
      },
      tableData: {
        key_66: [
          {
            prop_1:'',
            prop_2: '',
            prop_3: ''
          }
        ]
      },
    }
  },
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    row: {
      type: Array,
      default: () => []
    },
    columnAttrs: {
      type: Array,
      default: () => []
    }
  },
  methods: {
    updateColumnContentsAndAttributes(columns, prop, content, attributes, formKey = 'key_66') {
      // 给columns添加formDesc,用于判断生成表格的content类型
      this.formDesc[formKey].attrs.columns = [...columns]
      if (prop) {
        // 替换对应的content组件
        const column = this.formDesc[formKey].attrs.columns.find(col => col.prop === prop);
        if (column) {
          column['content'] = content;
        }

        // 替换对应的attribute
        let index =  this.formDesc[formKey].attributes.findIndex(item => item.prop === attributes.prop)
        if (index !== -1) {
          this.formDesc[formKey].attributes[index] = attributes
        }
        
        // 如果attribute的control为1，则添加到rules中
        if (attributes.control === 1) {
          this.formDesc[formKey].attrs.rules[attributes.prop] = { required: true, message: '必填' }
        }
      } else {
        // 修改值
        if (this.columnAttrs.length) {
          this.formDesc[formKey].attributes = this.columnAttrs
          return
        }
        // 初始化formDesc(添加默认的attributes和content组件类型为单行文本)
        this.formDesc[formKey].attrs.columns.forEach(item => {
          const attribute = {
            prop: item.prop,
            type: 0,
            numberType: 1,
            maxlength: 50,
            options: [],
            selectedOption: 1,
            control: 0
          }
          this.formDesc[formKey].attributes.push(attribute)
          item['content'] = COLUMN_TYPE[INPUT_TYPE.TEXT]
        })
      }
    },
    // 清空表格当前列数据
    clearTableData(tableData, prop) {
      tableData['key_66'].map(obj => {
        Object.keys(obj).forEach(key => {
          if (key === prop) {
            obj[key] = ''
          }
        })
        // 返回修改后的对象
        return obj
      })
    },
    handleRequestSuccess() { },
    handleRequest() { },
  },
  created() {
    this.updateColumnContentsAndAttributes(this.columns)
    if (this.row.length) {
      this.tableData['key_66'] = this.row
    }
    if (this.columnAttrs.length) {
      this.formDesc['key_66'].attributes = this.columnAttrs
    }
    this.$emit('SetTitle', '表格设计区')
    this.$emit('SetPageWidth', 1200)
    this.$emit('SetPageMinHeight', 500)
    this.$emit('SetPageMaxHeight', 1200)
    this.$emit('SetScroll', 'auto')
    this.$emit('SetPageActions', [
      {
        text: '确定',
        theme: 'primary',
        handle: () => {
          const obj = { ...this.formDesc['key_66'], default: this.tableData['key_66'] }
          this.$emit('Close', obj)
        }
      },
      {
        text: '取消',
        theme: 'primary',
        handle: () => {
          this.$emit('Close')
        }
      }
    ])
  },
  mounted() {
    // 监听表头按钮点击事件
    this.$bus.$on('handleHeader', (col) => {
      new this.$pageModal(
        setColumn,
        {
          props: {
            prop: col.property,
            attributes: this.formDesc['key_66'].attributes.filter(item => item.prop === col.property)[0]
          }
        },
        data => {
          if (data) {
            this.updateColumnContentsAndAttributes(this.columns, col.property, formatColumnContent(data), data)
            this.clearTableData(this.tableData, col.property)
          }
        }
      )
    })
    // 监听新增按钮
    this.$bus.$on('input', value => {
      this.tableData['key_66'] = value
    })
  },
  beforeDestroy() {
    this.$bus.$off('handleHeader')
    this.$bus.$off('input')
  },
}
</script>

<style lang="less" scoped>
/deep/thead {
  th:hover {
    cursor: pointer;
  }
}
/deep/.ivu-table-header .column {
  &:hover {
    cursor: pointer;
  }
}
.add_btn {
  margin-bottom: 20px;
}
/deep/.el-button {
  background: #f89c34;
  border: none;
}
// 给input-number添加百分号
/deep/.el-form .my-input-number {
  position: relative;
  &::after {
    content: '%';
    display: inline-block;
    height: 20px;
    line-height: 20px;
    width: 20px;
    text-align: center;
    position: absolute;
    right: 25%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>